<!-- 挑战 -->
<template>
    <div :class="['chal-index challenge',{'distance':inspectShow}]">
        <!-- 头部 -->
        <div class="chal-top clearfix">
            <div class="btn-return left" @click="goReturn()"></div>
            <div class="chal-type left">{{questionType}}</div>
            <div class="total-bar right">
                <span class="count">{{getCurNumber}}/{{questionList.length}}</span>
                <span class="progress-total" ref="progress-total">
                    <span class="progress-cur" ref="progress-cur"></span>
                </span>
            </div>
        </div>
        <!-- 内容 -->
        <transition name="page">
            <div :class="['chal-con',{'has-inspect':item.latitude && item.latitude!='0'},{'distance':inspectShow},{'istest':from == 'test'}]" v-if="item.isShow" v-for="(item,index) in questionList" :key="item.id">
                <div class="chal-con-box">
					<!-- 问题 -->
					<div class="title-box">
						<div class="text-issue" v-if="item.question">
							<p>{{item.question}}</p>
							<div class="img-box" v-if="item.imgeUrl">
								<img :src="item.imgeUrl" alt="">
							</div>
						</div>
						<div class="img-issue" v-else-if="item.imgeUrl && !item.question">
							<img :src="item.imgeUrl" alt="">
						</div>
					</div>
					<!-- 选项 -->
					<ul class="options" v-if="item.optionList && item.optionList.length > 0">
						<li :class="[{'fill':questionType=='填空题'},{'multiple':questionType=='多选题'},{'ischose':option.isChose},{'true':option.isCorrect==1},{'false':option.isCorrect==2}]" v-for="(option,inx) in item.optionList" :key="inx" @click="clickOption(option,item,index)" ref="option">
							<i><em v-show="option.isCorrect==0">{{questionType=='填空题' ? inx+1:optionListSign[inx]}}</em></i>
							<span v-if="questionType!='填空题'">{{option.con}}</span>
							<input type="text" v-if="questionType=='填空题'" v-model="option.value" placeholder="请输入你的答案">
						</li>
					</ul>
				</div>
				<div :class="['inspect',{'distance':inspectShow}]" v-show="item.latitude && item.latitude!='0' && from != 'test'">考察维度：{{item.latitudeStr}}</div>
				<div class="chal-btn" v-show="inspectShow" @click="answerSure(item,index)">提交</div>
				<div class="chal-end-btn clearfix" v-if="from == 'test' && (nowIndex+1) != questionList.length">
					<span class="left" @click="goLast()">上一题</span>
					<span class="right shadow2" @click="goNext()">下一题</span>
				</div>
				<div class="test-return" v-if="from == 'test' && (nowIndex+1) == questionList.length" @click="goList()">返回列表</div>
            </div>
        </transition>
    </div>
</template>

<script>
import { axGet, axPost } from '@/api/index'

export default {
    name: 'challenge',
    data() {
      return {
		from:this.$route.query.from,
        userid:this.$parent.myInfo.UserId,              // 用户id  
		bookid:this.$route.query.bookid,                // 书本编号 
		fromEnd:this.$route.query.fromend,              //是否来自结束页
		endIndex:this.$route.query.endindex,            //结果页查看第几题
		nowIndex:0,										//当前第几题
		questionType:'',  								// 题型 
		inspectShow:false,                              //是否有提交按钮
        optionListSign: [],                             // 英文字母  
        questionList: [],                               // 问题列表
        rightCount: 0,                                  // 答对数量
        isFirst: true,                                  // 正确按钮限制
		rightIndex: 0,                                  // 正确的索引
		task:{},
      }
	},
	computed: {
		getCurNumber() {
			let num = 0
			this.questionList.forEach((item,inxdex) => {
				if(item.isShow) {
					num = inxdex + 1;
					if(item.questionType==2 || item.questionType==3 || item.questionType==4){
						this.questionType='单选题'
					}else if(item.questionType==5){
						this.questionType='填空题'
					}else{
						this.questionType='多选题'
					}
				}
			})
			return num
		}
	},
	watch:{
        questionType(newVal,oldVal){
			if(newVal!='单选题' && this.fromEnd != 1){
               this.inspectShow=true;
            }else{
				this.inspectShow=false;
			}
		}
    },
    mounted() {
		this.$parent.menuShow=false;
		/****** 验证登录 *****/ 
		if(!sessionStorage.getItem("myInfo")){
			this.$router.replace({path:'/',query: {}});
		}else{
			this.getTaskInfo()
			for(let i = 0;i < 25;i++){//选项字母
				this.optionListSign.push(String.fromCharCode(65 + i))
			}
			if(this.fromEnd==1){
				this.questionList = JSON.parse(sessionStorage.getItem("questionList")) 
				this.questionList.forEach((item,index) => {
					item.isShow=false;
					if(index==this.endIndex){
						item.isShow=true;
					}
				})
			}else{
				this.getInit()
			}
			
			setTimeout(() => {
				this.progressStatus()
			}, 50)

			
		}
    },
    methods: {
		// 请求任务信息
        getTaskInfo(){
            axGet('GetBookCheckInTask', {
                userId:this.userid,
                bookid:this.bookid,
            }).then(res => {
                if(res.ResultCode==1){
                    this.task=res.Value
                }
            })
        },
		getInit() {
			// 获取题目信息
			axGet('GetBookQuestionList', {
				BookId: this.bookid
			}).then(res => {
				if(res.ResultCode === 1) {
					this.questionList = res.Value.list
					
					this.questionList.forEach((item,index) => {
						let optionList = []
						let answers=item.answer.split('_split_')
						if(item.questionType != 5){
							answers.sort(this.randomSort)
						}
						answers.forEach((a,i)=>{
							let list={
								isChose:false,
								isCorrect:0,
								con:a,
								value:'',//填空题
							}
							optionList.push(list)
						})
						this.$set(item,'optionList',optionList)

						let latitudeStr=''
						if(item.latitude){
							let latitude=item.latitude.split(',')
							latitude.forEach((l,i)=>{
								if(l==1){
									latitudeStr=latitudeStr+(i==0 ? '整体感知' : '，整体感知')
								}else if(l==2){
									latitudeStr=latitudeStr+(i==0 ? '获取信息' : '，获取信息')
								}else if(l==3){
									latitudeStr=latitudeStr+(i==0 ? '解释推断' : '，解释推断')
								}else if(l==4){
									latitudeStr=latitudeStr+(i==0 ? '鉴赏评价' : '，鉴赏评价')
								}
							})
						}
						
						this.$set(item,'latitudeStr', latitudeStr)
						this.$set(item,'isShow', false)
						this.$set(item,'myAnswer',[])//记录答题情况
						this.$set(item,'isCorrect',false)
						if(index == 0) {
							this.$set(item,'isShow', true)
						}
					})
				}
			})
		},
		// 排序规则
		randomSort() {
			return Math.random() > 0.5 ? -1 : 1
		}, 
		// 进度条状态
		progressStatus() {
			if(this.$refs['progress-total'] && this.$refs['progress-cur']) {
				this.$refs['progress-cur'].style.transitionDuration = '.5s'
				this.$refs['progress-cur'].style.webkitTransitionDuration = '.5s'
				this.$refs['progress-cur'].style.width =  this.getCurNumber / this.questionList.length * 100 + '%'
			}
		},
		clickOption(option,question,questionIndex) {
			if(this.isFirst && this.fromEnd != 1) {
				if(this.questionType=='单选题'){
					// this.singleChoice(option,question,questionIndex)
					option.isChose=!option.isChose
					this.answerSure(question,questionIndex)
				}else if(this.questionType=='多选题'){
					option.isChose=!option.isChose
				}
			}
		},

		//提交
		answerSure(question,questionIndex){
			if(this.isFirst){
				this.isFirst = false
				let rightAnswer=question.rightAnswer.split('_split_')
				let myAnswer=[]
				let isCorrect=1
				question.optionList.forEach((item,i)=>{
					if(this.questionType=='填空题'){
						if(item.value==rightAnswer[i]){//对应填空正确
							item.isCorrect=1
						}else{
							item.isCorrect=2
							isCorrect=2
						}
						myAnswer.push(item.value)
					}else{
						let hasAnswer=rightAnswer.find(ans => ans == item.con);
						if(item.isChose){//如果选中的错误则回答错误
							myAnswer.push(item.con)
							if(hasAnswer){
								item.isCorrect=1
							}else{
								item.isCorrect=2
								isCorrect=2
							}
							// for(let j=0;j<=rightAnswer.length;j++){
							// 	if(item.con==rightAnswer[j]){//选中内容是正确答案
							// 		item.isCorrect=1
							// 		break; 
							// 	}else{//选中内容不正确
							// 		item.isCorrect=2
							// 	}
							// }
							// if(item.isCorrect==2){
							// 	isCorrect=2
							// }
						}else{//如果有正确答案未选中的则回答错误
							if(hasAnswer){
								item.isCorrect=1
								isCorrect=2
							}
							// for(let j=0;j<=rightAnswer.length;j++){
							// 	if(item.con==rightAnswer[j]){
							// 		item.isCorrect=1
							// 		isCorrect=2
							// 		break; 
							// 	}
							// }	
						}
					}

				})
				question.myAnswer=myAnswer  //记录我的答案
				if(isCorrect==1){
					this.rightCount++ 
					question.isCorrect=true
				}
				this.nextQuestion(questionIndex)
			}
		},
		//下一题
		nextQuestion(questionIndex){
			setTimeout(() => { 
				this.questionList.forEach((item,i,arr) => {
					if(questionIndex === i && i != arr.length -1) { // 当前页翻页
						item.isShow = false
					}
					if(i - 1 === questionIndex) { // 切换题目
						item.isShow = true
					}
				})
				if(questionIndex + 1 != this.questionList.length){ // 不是最后一个问题
					this.$forceUpdate(); // 强制更新
					this.isFirst = true  // 初始化
					this.progressStatus() // 更新进度条
				}else { // 最后一个问题结束提交
					this.postAnswer()
				}
			},1000)
		},
		//上传答题情况
		postAnswer(){
			console.log('this.questionList',this.questionList)
			axPost('PostBookQuestionAnswerLog', {
                BookId:this.bookid,
				UserId:this.userid,
				isTest:1,	//1考试  0挑战
				taskid:this.task.taskId,
				AnswerQuestionCount: this.questionList.length,  	//总共多少题
				RightCount:this.rightCount,				//答对多少题
				answerRecord:JSON.stringify(this.questionList),			//新增打卡记录
            }).then(res => {
                if(res.ResultCode===1 && res.Value){
					let isPostScore=sessionStorage.getItem("postScore3")
                    if(isPostScore && isPostScore=='true'){
                        console.log('今天已经获得积分')
                    }else{
                        let score=Math.round(this.rightCount/this.questionList.length*100)
                        this.$parent.postScore(score,3,'完成挑战!')
					}
					sessionStorage.setItem("questionList",JSON.stringify(this.questionList))
					this.$router.replace({path:'/challengeEnd',query: {bookid:this.bookid,rightcount:this.rightCount}}); 
                }else{
					this.$LayerTip({
                        content:"提交失败，请稍后再试",
                        time:1500,
                    });
				}
            })
		},
		// 返回
		goReturn() {
			this.$router.go(-1)
		},
		//考试相关 
		goLast(){
			this.questionList.forEach((item,i,arr) => {
				if(this.nowIndex === i && i != 0) { // 当前页翻页
					item.isShow = false
				}
				if(i + 1 === this.nowIndex) { // 切换题目
					item.isShow = true
				}
			})
			if(this.nowIndex != 0){ // 不是最后一个问题
				this.progressStatus() // 更新进度条
				this.nowIndex--
			}else { // 最后一个问题
				
			}
		},
		goNext(){
			this.questionList.forEach((item,i,arr) => {
				if(this.nowIndex === i && i != arr.length -1) { // 当前页翻页
					item.isShow = false
				}
				if(i - 1 === this.nowIndex) { // 切换题目
					item.isShow = true
				}
			})
			if(this.nowIndex+1 != this.questionList.length){ // 不是最后一个问题
				this.progressStatus() // 更新进度条
				this.nowIndex++
			}else { // 最后一个问题
				
			}
		},
		goList(){
			this.$router.go(-2)
		},
    }
}
</script>

<style type="text/css" scoped>
.chal-index{
	padding-top: 1.1rem;
	padding-bottom: 0.3rem;
}
.chal-index.distance{
	padding-bottom: 0.8rem;
}
/* 头部 */
.chal-top {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
    height: 1.1rem;
    line-height: 1.1rem;
	color: #fff;
	padding: 0 0.32rem;
	box-sizing: border-box;
}
.btn-return {
    width: .64rem;
    height: 100%;
    background: url(~@/assets/img/icon/return.png) no-repeat 0 center;
    background-size: contain;
}
.chal-type{
    font-size: 0.34rem;
    padding-left: 0.2rem;
    font-weight: bold;
}
.total-bar {
  	height: 100%;
}
.total-bar .count {
	font-size: 0.36rem;
	font-weight: bold;
	padding-right: 0.1rem;
}
.progress-total{
	width: 2.4rem;
	height: 0.3rem;
	box-sizing:border-box;
	-webkit-box-sizing:border-box;
	background: #fff;
	border-radius: 0.16rem;
	display: inline-block;
	position: relative;     
}
.progress-cur{
	position: absolute;
	left: 0;
	top: 0; 
	width: 0;
	height: 100%;
	background: #ffd300;
	border-radius: 0.16rem;
}

/* 内容 */
.chal-con{
  	padding: 0.46rem 0.6rem;
}
.chal-con.has-inspect{
	padding-bottom: 0.9rem;
}
.chal-con.distance{
	padding-bottom: 1.3rem;
}
.chal-con.istest{
	padding-bottom: 1.5rem;
}
.title-box{
	padding-bottom: 0.3rem;
	/* min-height: 3rem; */
}
.text-issue p {
	font-size: .32rem;
	font-weight: bold;
	line-height: 0.56rem;
	padding-bottom: 0.08rem;
}
.text-issue .img-box {
	height: 2.68rem;
  	text-align: center;
}
.text-issue .img-box img {
  	height: 100%;
}
.img-issue {
	height: 3.3rem;
	text-align: center;
}
.img-issue img{
  	height: 100%;
}

/* 选项 */
.options li{
	margin-bottom: .2rem;
	padding: 0.22rem 0 0.22rem 0.28rem;
	border-radius: .2rem;
	background: #f3f5f7;
}
.options li.fill{
	background: #fff;
	border: 0.04rem solid #eee;
}
.options li i{
	display: inline-block;
	margin-right: .22rem;
	width: 0.56rem;
	height: 0.56rem;
	line-height: 1;
	padding-top: 0.06rem;
	border-radius: 50%;
	text-align: center;
	vertical-align: middle;
	color: #02affe;
	font-size: 0.36rem;
	font-weight: bold;
	border: 0.04rem solid #02affe;
	box-sizing: border-box;
}
.options li span {
  display: inline-block;
  width: calc(100% - 1.08rem);
  line-height: 0.4rem;
  vertical-align: middle;
  font-size: .3rem;
}
.options li input {
  display: inline-block;
  width: calc(100% - 1.4rem);
  vertical-align: middle;
  font-size: .32rem;
}
.options li input::-webkit-input-placeholder{
	color: #ccc;
}
.options li input::-moz-placeholder{
	color: #ccc;
}
.options li input:-moz-placeholder{
	color: #ccc;
}
.options li input:-ms-input-placeholder{
	color: #ccc;
}

.options li.multiple i{
	border-radius: 0.14rem;
}
.options li.ischose i{
	color: #fff;
	background: #02affe;
}
.options li.true{
	color: #00cd86;
	background: #e5faf3;
	border-color: #e5faf3;
}
.options li.false {
   color: #ff7100;
   background: #fff1e5;
   border-color:#fff1e5;
}
.options li.true i{
	border: 0;
	background: #00cd86 url(~@/assets/img/icon/chal-true.png) no-repeat center center;
	background-size: auto 0.22rem;
}
.options li.false i{
	border: 0;
	background: #ff7100 url(~@/assets/img/icon/chal-false.png) no-repeat center center;
	background-size: 0.23rem 0.23rem;
}
.options li.true input{
	color: #00cd86;
	background: #e5faf3;
}
.options li.false input{
	color: #ff7100;
	background: #fff1e5;
}

.inspect{
	width: 100%;
	padding:0 0.6rem;
	box-sizing: border-box;
	position: absolute;
	left: 0;
	bottom: 0.46rem;
	text-align: center;
	color: #999;
}
.inspect.distance{
	bottom: 0.86rem;
}
.chal-end-btn{
    text-align: center;
    font-size: 0.36rem;
    width: 100%;
    padding: 0 0.5rem;
    box-sizing: border-box;
    position: absolute;
    left: 0;
    bottom: 0.48rem;
}
.chal-end-btn span{
    width: 47.5%;
    height: 0.96rem;
    line-height: 0.96rem;
    border-radius: 0.5rem;
}
.chal-end-btn .left{
    border: 1px solid #e0e0e0;
    color: #666;
    box-shadow: 0 0.1rem 0.2rem rgba(224,224,224,.3);
    -webkit-box-shadow: 0 0.1rem 0.2rem rgba(224,224,224,.3);
}
.chal-end-btn .right{
    background: #02affe;
    color: #fff;
    border: 1px solid #02affe;
}
.test-return{
	width: 3.6rem;
	height: 1rem;
	line-height: 1rem;
	border-radius: 0.5rem;
	text-align: center;
	font-size: 0.36rem;
	position: absolute;
    left: 50%;
    bottom: 0.48rem;
	margin-left: -1.8rem;
	background: #ffd300;
	color: #8f520f;
	box-shadow: 0 0.1rem 0.2rem rgba(255,211,0,.25);
}
</style>